// pages/mine/mine.js
const app = getApp();

Page({
  data: {
    // 登录相关
    isLoggedIn: false,
    loginType: 'admin', // 'admin' 或 'user'
    username: '',
    password: '',
    loginError: '',
    userType: '', // '主理人' 或 '普通用户'
    
    // 用户信息获取相关
    canIUseNicknameComp: false,
    canIUseGetUserProfile: false,
    hasUserInfo: false,
    userInfo: {
      avatarUrl: '/images/default-avatar.png',
      nickName: ''
    },
    
    // 其他原有数据
    isAdmin: false,
    userBalance: 0,
    showAvoidModal: false,
    selectedAvoid: '没有忌口',
    simpleAvoidOptions: ['没有忌口', '不吃辣', '少辣', '不吃葱姜蒜', '不吃香菜', '不吃海鲜', '素食'],
    showBalanceModal: false,
    showAddModal: false,
    userId: '',
    balanceAmount: '',
    errorMsg: '',
    categories: ['家常小炒', '时令素菜', '蒸煮鲜食', '荤素炖菜', '凉拌小菜', '家常汤羹', '小酒饮料'],
    categoryIndex: 0,
    dishName: '',
    dishIngredients: '',
    preciousIngredients: '',
    cart: [],
    cartCount: 0,
    adminPassword: '123456'
  },

  onLoad: function(options) {
    // 检查基础库版本
    this.checkBaseLibraryVersion();
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 加载其他数据
    const adminPassword = wx.getStorageSync('adminPassword') || '123456';
    const searchHistory = wx.getStorageSync('searchHistory') || [];
    const cart = wx.getStorageSync('cart') || [];
    const cartCount = cart.reduce((total, item) => total + item.quantity, 0);
    
    // 加载忌口设置
    const savedAvoid = wx.getStorageSync('selectedAvoid') || '没有忌口';
    
    this.setData({
      adminPassword,
      searchHistory,
      cart,
      cartCount,
      selectedAvoid: savedAvoid
    });

    if (app && app.globalData) {
      app.globalData.adminPassword = adminPassword;
    }
  },
   // 切换选择状态
   toggleAvoid(e) {
    const item = e.currentTarget.dataset.item;
    let selectedAvoids = this.data.selectedAvoids;
    
    const index = selectedAvoids.indexOf(item);
    if (index > -1) {
      // 如果已选中，则移除
      selectedAvoids.splice(index, 1);
    } else {
      // 如果未选中，则添加
      selectedAvoids.push(item);
    }
    
    this.setData({
      selectedAvoids: selectedAvoids
    });
  },
  // 确认选择
  confirmAvoidSelection() {
    wx.setStorageSync('selectedAvoid', this.data.selectedAvoid);
    const selectedAvoids = this.data.selectedAvoids;
    
    if (selectedAvoids.length === 0) {
      wx.showToast({
        title: '请至少选择一项',
        icon: 'none'
      });
      return;
    }
    
    // 保存选择结果
    this.saveAvoidPreferences(selectedAvoids);
    
    // 关闭弹窗
    this.setData({
      showAvoidModal: false
    });
    
    wx.showToast({
      title: '忌口偏好已保存',
      icon: 'success'
    });
    
    console.log('用户选择的忌口:', selectedAvoids);
  },

  // 清空所有选择
  clearAvoidSelection() {
    this.setData({
      selectedAvoids: []
    });
  },

  // 跳过选择
  skipAvoidSelection() {
    this.setData({
      showAvoidModal: false,
      selectedAvoids: [] // 清空选择
    });
    
    wx.showToast({
      title: '已跳过忌口选择',
      icon: 'none'
    });
  },

  // 保存忌口偏好
  saveAvoidPreferences(avoidList) {
    // 保存到本地存储
    wx.setStorageSync('userAvoidPreferences', avoidList);
    
    // 或者保存到全局数据
    getApp().globalData.userAvoids = avoidList;
    
    // 这里可以调用API保存到服务器
    // this.saveToServer(avoidList);
  },

  // 如果需要，可以添加全选功能
  selectAllAvoids() {
    this.setData({
      selectedAvoids: [...this.data.avoidOptions]
    });
  },
  onShow: function() {
    // 每次显示页面时检查登录状态
    this.checkLoginStatus();
    
    // 加载其他数据
    const adminPassword = wx.getStorageSync('adminPassword') || '123456';
    const cart = wx.getStorageSync('cart') || [];
    const cartCount = cart.reduce((total, item) => total + item.quantity, 0);
    const savedAvoid = wx.getStorageSync('selectedAvoid') || '没有忌口';

    if (this.data.adminPassword !== adminPassword) {
      this.setData({ adminPassword });
      if (app && app.globalData) {
        app.globalData.adminPassword = adminPassword;
      }
    }
    
    this.setData({ 
      cart, 
      cartCount,
      selectedAvoid: savedAvoid
    });
  },

  // 检查基础库版本
  checkBaseLibraryVersion: function() {
    // 检查是否支持昵称输入组件
    if (wx.canIUse('input.type.nickname')) {
      this.setData({
        canIUseNicknameComp: true
      });
    }
    
    // 检查是否支持getUserProfile
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }
  },

  // 切换登录类型
  switchLoginType: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      loginType: type,
      loginError: ''
    });
  },

  // 检查登录状态
  checkLoginStatus: function() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    const userType = wx.getStorageSync('userType');
    
    if (token && userInfo) {
      this.setData({
        isLoggedIn: true,
        userInfo: userInfo,
        userType: userType,
        isAdmin: userType === '主理人'
      });
      
      // 更新全局状态
      if (app.globalData) {
        app.globalData.isAdmin = userType === '主理人';
        app.globalData.userInfo = userInfo;
      }
    } else {
      this.setData({
        isLoggedIn: false,
        isAdmin: false,
        userInfo: {
          avatarUrl: '/images/default-avatar.png',
          nickName: '未登录用户'
        }
      });
    }
  },

  // 用户名输入
  onUsernameInput: function(e) {
    this.setData({
      username: e.detail.value,
      loginError: ''
    });
  },

  // 密码输入
  onPasswordInput: function(e) {
    this.setData({
      password: e.detail.value,
      loginError: ''
    });
  },

  // 主理人登录处理
  handleAdminLogin: function() {
    const { username, password } = this.data;
    
    // 简单验证
    if (!username || !password) {
      this.setData({
        loginError: '请输入用户名和密码'
      });
      return;
    }
    
    // 模拟登录请求
    wx.showLoading({
      title: '登录中...',
    });
    
    // 模拟API请求延迟
    setTimeout(() => {
      wx.hideLoading();
      
      // 模拟登录成功
      if (username === 'admin' && password === '123456') {
        const userInfo = {
          nickName: '私厨主理人',
          avatarUrl: '/images/chef-avatar.png'
        };
        
        // 保存登录状态到本地存储
        wx.setStorageSync('token', 'mock-token-' + Date.now());
        wx.setStorageSync('userInfo', userInfo);
        wx.setStorageSync('userType', '主理人');
        
        this.setData({
          isLoggedIn: true,
          userInfo: userInfo,
          userType: '主理人',
          isAdmin: true,
          loginError: ''
        });
        
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });
        
        // 跳转到首页
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
      } else {
        this.setData({
          loginError: '用户名或密码错误'
        });
      }
    }, 1500);
  },

  // 选择头像
  /**
   * 处理用户选择头像的回调函数
   * @param {Object} e - 事件对象
   * @param {string} e.detail.avatarUrl - 用户选择的头像URL
   * 设置用户头像URL，如果已有昵称则标记用户信息已完善
   */
  onChooseAvatar: function(e) {
    const { avatarUrl } = e.detail;
    this.setData({
      'userInfo.avatarUrl': avatarUrl
    });
    
    // 如果有昵称，则设置hasUserInfo为true
    if (this.data.userInfo.nickName) {
      this.setData({
        hasUserInfo: true
      });
    }
  },

  // 输入昵称
  onInputChange: function(e) {
    const nickName = e.detail.value;
    this.setData({
      'userInfo.nickName': nickName
    });
    
    // 如果有头像，则设置hasUserInfo为true
    if (this.data.userInfo.avatarUrl && nickName) {
      this.setData({
        hasUserInfo: true
      });
    }
  },

  // 获取用户信息（兼容旧版本）
  getUserProfile: function() {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
      },
      fail: (err) => {
        console.log('获取用户信息失败', err);
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      }
    });
  },

  // 微信授权登录
  onGetUserInfo: function(e) {
    const { avatarUrl } = this.data.userInfo;
    if (e.detail.userInfo) {
      // 用户同意授权
      wx.showLoading({
        title: '登录中...',
      });
      
      // 模拟API请求延迟
      setTimeout(() => {
        wx.hideLoading();
        let u = e.detail.userInfo;
        u.avatarUrl = avatarUrl;
        // 保存登录状态到本地存储
        wx.setStorageSync('token', 'wechat-token-' + Date.now());
        wx.setStorageSync('userInfo', u);
        wx.setStorageSync('userType', '普通用户');
        
        this.setData({
          isLoggedIn: true,
          userInfo: u,
          userType: '普通用户',
          isAdmin: false,
          loginError: ''
        });
        
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });
        
        // 跳转到首页
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
      }, 1500);
    } else {
      // 用户拒绝授权
      wx.showToast({
        title: '授权失败',
        icon: 'none'
      });
    }
  },

  // 退出登录
  handleLogout: function() {
    wx.showModal({
      title: '确认退出',
      content: '您确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('userType');
          
          this.setData({
            isLoggedIn: false,
            username: '',
            password: '',
            userInfo: {
              avatarUrl: '/images/default-avatar.png',
              nickName: '未登录用户'
            },
            userType: '',
            isAdmin: false,
            hasUserInfo: false
          });
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  // 进入首页
  goToHomepage: function() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 其他原有功能函数保持不变...
  tasteDetail: function() {
    this.setData({
      showAvoidModal: true
    });
  },

  selectSimpleAvoid: function(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      selectedAvoid: item
    });
  },

  hideAvoidModal: function() {
    this.setData({
      showAvoidModal: false
    });
  },

  goToAdmin: function() {
    wx.navigateTo({
      url: '/pages/admin/admin'
    });
  },

  navigateToDishAdmin: function() {
    wx.navigateTo({
      url: '/pages/dish-admin/dish-admin'
    });
  },

  navigateToOrderAdmin: function() {
    wx.navigateTo({
      url: '/pages/order-admin/order-admin'
    });
  },

  navigateToMyOrders: function() {
    wx.navigateTo({
      url: '/pages/order/order'
    });
  },

  showBalanceDetail: function() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  showAddBalanceModal: function() {
    this.setData({
      showBalanceModal: true,
      userId: '',
      balanceAmount: '',
      errorMsg: ''
    });
  },

  hideBalanceModal: function() {
    this.setData({
      showBalanceModal: false
    });
  },

  onUserIdInput: function(e) {
    this.setData({
      userId: e.detail.value
    });
  },

  onBalanceAmountInput: function(e) {
    this.setData({
      balanceAmount: e.detail.value
    });
  },

  addUserBalance: function() {
    const { userId, balanceAmount } = this.data;
    
    if (!userId) {
      this.setData({ errorMsg: '请输入用户ID' });
      return;
    }
    
    if (!balanceAmount || balanceAmount < 1 || balanceAmount > 1000) {
      this.setData({ errorMsg: '请输入1-1000之间的数量' });
      return;
    }
    
    wx.showToast({
      title: '添加成功',
      icon: 'success'
    });
    
    this.hideBalanceModal();
  }
});